package cn.cmdr.controller;

import cn.cmdr.pojo.Staff;
import cn.cmdr.service.StaffService;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import cn.cmdr.vo.ResultVo;
import cn.cmdr.vo.StaffVo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Controller
@Slf4j
public class LoginController {
    @Resource
    private StaffService staffService;
    @PostMapping("/staffList")
    public ResultVo getStaffList() {
        List<Staff> list = staffService.getStaffList();
        return ResultVo.sucess(list);
    }

    @PostMapping("/login")
    public String dologin(String userCode,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode,password);
        subject.login(token);
        return "redirect:/index";
    }

    @ExceptionHandler({RuntimeException.class})
    public void handlerException(RuntimeException e, Model model) {
        String msg = "";
        if (e instanceof UnknownAccountException) {
            msg = "用户名错误或被禁用";
        } else if (e instanceof IncorrectCredentialsException) {
            msg = "密码错误";
        } else {
            msg = "其他错误";
        }
        model.addAttribute("loginErr",msg);
    }
}